import { useEffect, useState, useRef } from 'react'
/* -------------------------------------------------------- Declare -- */
const { $lazy, $http, $fn, $config } = window
/* -------------------------------------------------------- Async Component -- */
import $time from '@utils/time'
const SearchTable = $lazy.hook(()=>import('#cpt/temp/SearchTable'))
const className = 'nosel cp abs_full fxm pl5'
const isNative = $config.isNative
/* -------------------------------------------------------- Page Component -- */
const obj = {}
export const Component = () => {
	const user = $fn.getUser()
	const tableRef = useRef()
	const { t, d } = $fn.query()
	const table_name = t
	const database = d
	const [ cols, setCols ] = useState([])
	const [ add, setAdd ] = useState([])
	const is_seaql = table_name === 'seaql_migrations'
	
	const onEdit = ({ e, form, t, r }) => {
		e.stopPropagation()
		window.$formModalRef().open({
			modal:{
				title 	: <span>修改【<b className='c3 ar'>{form.label}</b>】</span>,
				width 	: '40%',
			},
			form: {
				labelWidth: 's8',
				api: 'mysql/table_data/update',
				way:'put',
				infoApi : false,
				param : { [form.name] : t },
				x: 0,
				setNewParam : data => {
					let update = []
					for(let i in data){
						let v = data[i]
						let type = obj[i]
						if( type === 'json' ){
							v = JSON.stringify(v)
						}else {
							v = `'${v}'`
						}
						v = v === '' || v === undefined ? null : v
						update.push(`${i}=${v}`)
					}
					return { id: r.id, database, table_name, update }
				},
				data: [ form ],
				onOk : () => {
					window.$.ref(tableRef).tableRef().search({ scroll:0 })
				}
			}
		})
	}
	
	useEffect(()=>{
		$http.pull(null, 'mysql/structure', { param: { table_name, database } }).then(data=>{
			let col = []
			let d = data.map( ({ Type, Field, Null }) => {
				let type = {}
				if( Type === 'bool' || Type === 'boolean' || Type === 'tinyint(1)' ){
					type = { type:'radio', mode:'button' }
				}else if( Type.includes('int') || Type.includes('decimal') || Type.includes('float') || Type.includes('double') ){
					type = { type:'number', money:'-1' }
				}else if( Type === 'date' ){
					type = { type:'date' }
				}else if( Type === 'date_time' || Type === 'timestamp' ){
					type = { type:'date', format: 1 }
				}else if( Type === 'text' || Type === 'json' || Type.includes('blob') || Type.includes('binary') ){
					type = { type:'textarea', maxLength: null }
				}
				if( Field === 'mark' ) type = { type:'textarea', maxLength: null, rows:'5' }
				
				obj[Field] = Type
				let value = {}
				if( Field === 'create_user' && Null === 'NO' ) value = { value: 1000, type: 'number'}
				
				let form = { label: Field, name:Field, ...type, ...value, r:  Field !== 'id' && Null === 'NO', rule:0  }
				col.push({ title: Field, dataIndex: Field, width:150, ellipsis:1, sorter:1, render: (t,r) =>{
					if($fn.isArray( t ) || $fn.isObject( t )) {
						t = JSON.stringify(t)
					}
					if( Type === 'timestamp' && t ){
						t = $time.format(t, {t:'full'})
					}
					return ['id', 'uuid', 'update_user','create_time','update_time'].includes(Field) 
						?
						t
						:
						<div className={className} onClick={e => onEdit({ e, form, t, r }) }>{t}</div>
				} })
				return form
			})
			d = d.filter( v => ![ 'id', 'uuid', 'update_user','create_time','update_time'].includes(v.name) )
			setCols( col )
			setAdd( d )
		})
	},[table_name, database]) // eslint-disable-line
	
	// 编辑添加配置
	const addConfig = {
		modal: {
			width 		: '45%',
		},
		form: {
			labelWidth 	: 's8',
			setNewParam: (data, { mod }) => {
				let names = []
				let values = []
				let update = []
				for(let i in data){
					let v = data[i] ?? null
					if( v ){
						let type = obj[i]
						if( type === 'json' ){
							v = JSON.stringify(v)
						}else {
							v = `'${v}'`
						}
						if(mod) {
							update.push(`${i}=${v}`)
						}else{
							names.push(i)
							values.push(v)
						}
					}else{
						if(mod) {
							v  = v === '' || v===undefined ? null : v
							update.push(`${i}=${v}`)
						}
					}
				}
				let d =  mod ? { id:data.id, update } : { names, values }
				return {  database, table_name, ...d }
			},
			backData : data => {
				for(let i in data){
					let v = data[i]
					let type = obj[i]
					
					if( v === null ){
						data[i] = ''
					}else{
						if( type === 'json'){
							data[i] = JSON.stringify(v)
						}
					}
				}
				return data
			},
			data: add
		}
	}
	const config = {
		page : {
			title: '表数据' + ' - ' + database + ' - ' + table_name,
			controls	: [
				user.role != 0 ? null : { label:'id 排序', mode:'confirm', abs:0, rc:1, ghost:1, api: 'mysql/sort_id', param: { id: table_name, database }},
				user.role != 0 ? null : { label:'清空表', mode:'confirm', ghost:1, rc:1, abs:0, api: 'mysql/truncate_table', param: { table_name:[ table_name ], database }},
				!isNative ? null : { label:'删除全部', mode:'confirm', ghost:1, rc:1, abs:0, api: 'mysql/delete_table', param: { table_name:[ table_name ], database }},
				!isNative ? null : { label:'新增', mode:'add', r:1 },
				!isNative ? null : { label:'多选删除', mode:'del', abs:0, way:'put', param:({ keys }) => ({ id:keys, database, table_name } ) },
				{ mode:'refresh'},
				{ mode:'back' }
			] 
		},
		search : {
			query: { table_name, database },
			data:[
				{ label: '项目名称', 	name:'title' },
			]
		},
		table: {
			api 		: 'mysql/table_data',
			addApi 		: 'mysql/table_data/add',
			modApi 		: 'mysql/table_data/update',
			delApi 		: 'mysql/table_data/del',
			className 	: 'jz-table-data',
			addConfig,
			idStr 		: is_seaql ? 'version' : 'id',
			cols,
			row 		: isNative ? {} : null,
			controls 	: is_seaql ? null : {
				width: 160,
				data: ({ id }) => [
					{ mode:'mod', config:addConfig, rs:0, param:{ id }, infoApi:'mysql/table_data/find', backParam:{ id, database, table_name } }, 
					{ mode:'delPop', abs:0, way:'put', param:{ id:[id], database, table_name } },
				]
			}
		}
	}
	return cols.length > 0 ? <SearchTable {...config} ref={tableRef}/> : null
}
export default Component